package com.hbplat.shardingsphere.util;

import com.hbplat.shardingsphere.domain.ExcelEntity;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 　　* @description: TODO
 * 　　* @param
 * 　　* @return
 * 　　* @throws
 * 　　* @author 陈宇
 * 　　* @date $ $
 *
 */
public class FileUtil {

    /**
     * 获取网络附件
     * @param url
     * @return
     */
    public static File getUrlFile(String url,String fileName){
        //需要判断文件是否已存在，如已存在，则需要修改附件名
        File file1 = new File(ExcelEntity.getPath()+fileName);
        int i = 1;
        //文件名,如spring
        String name = fileName.substring(0,fileName.indexOf("."));
        //文件后缀,如.jpeg
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        while (file1.exists()){
            String newFilename = name+"("+i+")"+suffix;
            file1 = new File(ExcelEntity.getPath()+newFilename);
            i++;
        }
        if(StringUtil.isNotEmpty(url)){
            try {
                URL url1 = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
                InputStream inputStream = conn.getInputStream();
                int index;
                byte[] bytes = new byte[1024];
                FileOutputStream downloadFile = new FileOutputStream(file1.getPath());
                while ((index = inputStream.read(bytes)) != -1) {
                    downloadFile.write(bytes, 0, index);
                    downloadFile.flush();
                }
                downloadFile.close();
                inputStream.close();
                downloadFile = null;
                inputStream = null;
                if(!file1.exists()){
                    return null;
                }
                return file1;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 获取网络附件
     * @param url
     * @return
     */
    public static File getUrlFile2(String url,String fileName,String path){
        //需要判断文件是否已存在，如已存在，则需要修改附件名
        File file1 = new File(path+File.separator+fileName);
        int i = 1;
        //文件名,如spring
        String name = fileName.substring(0,fileName.indexOf("."));
        //文件后缀,如.jpeg
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        while (file1.exists()){
            String newFilename = name+"("+i+")"+suffix;
            file1 = new File(path+File.separator+newFilename);
            i++;
        }
        if(StringUtil.isNotEmpty(url)){
            try {
                URL url1 = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
                InputStream inputStream = conn.getInputStream();
                int index;
                byte[] bytes = new byte[1024];
                FileOutputStream downloadFile = new FileOutputStream(file1.getPath());
                while ((index = inputStream.read(bytes)) != -1) {
                    downloadFile.write(bytes, 0, index);
                    downloadFile.flush();
                }
                downloadFile.close();
                inputStream.close();
                downloadFile = null;
                inputStream = null;
                if(!file1.exists()){
                    return null;
                }
                return file1;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void zipFiles(List<File> fileList, File zipFile) {
        if(null == fileList || 0 == fileList.size()){
            return;
        }
        // 判断压缩后的文件存在不，不存在则创建
        if (!zipFile.exists()) {
            try {
                zipFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 创建 FileOutputStream 对象
        FileOutputStream fileOutputStream = null;
        // 创建 ZipOutputStream
        ZipOutputStream zipOutputStream = null;
        // 创建 FileInputStream 对象
        FileInputStream fileInputStream = null;
        try {
            // 实例化 FileOutputStream 对象
            fileOutputStream = new FileOutputStream(zipFile);
            // 实例化 ZipOutputStream 对象
            zipOutputStream = new ZipOutputStream(fileOutputStream);
            // 创建 ZipEntry 对象
            ZipEntry zipEntry = null;
            // 遍历源文件数组
            for (int i = 0; i < fileList.size(); i++) {
                // 将源文件数组中的当前文件读入 FileInputStream 流中
                if(null == fileList.get(i)){
                    continue;
                }
                if(!fileList.get(i).exists()){
                    continue;
                }
                fileInputStream = new FileInputStream(fileList.get(i));
                // 实例化 ZipEntry 对象，源文件数组中的当前文件
                zipEntry = new ZipEntry(fileList.get(i).getName());
                if(StringUtil.isEmpty(fileList.get(i).getName()) || "null".equals(fileList.get(i).getName())){
                    System.out.println(fileList.get(i));
                }
                System.out.println(fileList.get(i).getPath()+"====="+zipEntry.getName());
                zipOutputStream.putNextEntry(zipEntry);
                // 该变量记录每次真正读的字节个数
                int len;
                // 定义每次读取的字节数组
                byte[] buffer = new byte[1024];
                while ((len = fileInputStream.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }
            }
            if(null != zipOutputStream){
                zipOutputStream.closeEntry();
                zipOutputStream.close();
            }
            if(null != fileInputStream){
                fileInputStream.close();
                fileOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            for (int i = 0; i < fileList.size(); i++) {
                System.out.println("path:"+fileList.get(i).getPath()+"====name:"+fileList.get(i).getName());
            }
        }

    }

    /**
     * xls 转 pdf
     * @param xlsUrl
     * @param pdfUrl
     */
    public static void excelToPdf(String xlsUrl, String pdfUrl) {
        ActiveXComponent ax = null;
        Dispatch excel = null;
        try {
            ComThread.InitSTA();
            ax = new ActiveXComponent("Excel.Application");
            ax.setProperty("Visible", new Variant(false));
            //禁用宏
            ax.setProperty("AutomationSecurity", new Variant(3));

            Dispatch excels = ax.getProperty("Workbooks").toDispatch();

            Object[] obj = {
                    xlsUrl,
                    new Variant(false),
                    new Variant(false)
            };

            excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();

            //转换格式
            Object[] obj2 = {
                    //PDF格式等于0
                    new Variant(0),
                    pdfUrl,
                    //0=标准（生成的PDF图片不会模糊），1=最小的文件
                    new Variant(0)
            };

            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, obj2, new int[1]);

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (excel != null) {
                Dispatch.call(excel, "Close", new Variant(false));
            }
            if (ax != null) {
                ax.invoke("Quit", new Variant[]{});
                ax = null;
            }
            ComThread.Release();
        }
    }
}
